const app = getApp()
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    planId: '',
    plan: null,
    stats: null,
    allocations: [],
    loading: true
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/production-plan-detail/production-plan-detail')) {
      return
    }
    
    if (options.id) {
      this.setData({
        planId: options.id
      })
      this.loadPlanDetail()
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  onShow() {
    if (this.data.planId) {
      this.loadPlanDetail()
    }
  },

  // 加载生产计划详情
  loadPlanDetail() {
    this.setData({ loading: true })
    
    app.request({
      url: '/getProductionPlanDetail',
      method: 'GET',
      data: { id: this.data.planId }
    }).then(res => {
      this.setData({ loading: false })
      if (res.code === 1) {
        const planData = res.data
        this.setData({
          plan: planData,
          stats: planData.stats,
          allocations: planData.allocations || []
        })
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: planData.plan_name || '生产计划详情'
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载生产计划详情失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 分配工序
  allocateProcess() {
    wx.navigateTo({
      url: `/pages/allocate-production-plan/allocate-production-plan?planId=${this.data.planId}`
    })
  },

  // 查看进度
  viewProgress() {
    wx.navigateTo({
      url: `/pages/production-plan-progress/production-plan-progress?planId=${this.data.planId}`
    })
  },

  // 编辑计划
  editPlan() {
    wx.navigateTo({
      url: `/pages/edit-production-plan/edit-production-plan?id=${this.data.planId}`
    })
  },

  // 开始计划
  startPlan() {
    wx.showModal({
      title: '确认开始',
      content: '确定要开始这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus('start')
        }
      }
    })
  },

  // 暂停计划
  pausePlan() {
    wx.showModal({
      title: '确认暂停',
      content: '确定要暂停这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus('pause')
        }
      }
    })
  },

  // 恢复计划
  resumePlan() {
    wx.showModal({
      title: '确认恢复',
      content: '确定要恢复这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus('resume')
        }
      }
    })
  },

  // 完成计划
  completePlan() {
    wx.showModal({
      title: '确认完成',
      content: '确定要完成这个生产计划吗？',
      success: (res) => {
        if (res.confirm) {
          this.updatePlanStatus('complete')
        }
      }
    })
  },

  // 更新计划状态
  updatePlanStatus(action) {
    wx.showLoading({ title: '处理中...' })
    
    const actionMap = {
      start: 'startProductionPlan',
      pause: 'pauseProductionPlan',
      resume: 'resumeProductionPlan',
      complete: 'completeProductionPlan'
    }
    
    app.request({
      url: `/${actionMap[action]}`,
      method: 'POST',
      data: { id: this.data.planId }
    }).then(res => {
      wx.hideLoading()
      if (res.code === 1) {
        wx.showToast({
          title: res.msg || '操作成功',
          icon: 'success'
        })
        this.loadPlanDetail()
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('更新计划状态失败:', err)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    })
  },

  // 查看分工详情
  viewAllocationDetail(e) {
    const allocationId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/allocation-detail/allocation-detail?id=${allocationId}`
    })
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: '未开始',
      1: '进行中',
      2: '已暂停',
      3: '已完成'
    }
    return statusMap[status] || '未知'
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      0: '#999',
      1: '#07c160',
      2: '#ff976a',
      3: '#1989fa'
    }
    return colorMap[status] || '#999'
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '-'
    const date = new Date(timestamp * 1000)
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
  }
})
